<template>
    <div class="addrList"  :style="'height: ' + pageHeight + 'px;overflow: scroll;'">
      <jm-head ref="head"></jm-head>
         <div>
            <div class="addrList_menu box">
                <van-address-list
                    v-model="defaultAddr"
                    :list="addrList"
                    :switchable="hasOrder"
                    default-tag-text="默认"
                    add-button-text="新增地址"
                    @select="active"
                    @add="onAdd"
                    @edit="onEdit"
                >
                <div style="width: 100%;height: 70px;"></div>
                </van-address-list>

            </div>
            <van-empty class="vant-image" description="暂无地址" image="https://meibaolianmeng.oss-cn-beijing.aliyuncs.com/cdn/address.png?x-oss-process=image/interlace,1/format,png"  v-if = "!haveLists"></van-empty>
         </div>
         <van-action-sheet
           v-model="showModel"
           :actions="actions"
           cancel-text="取消"
          :close-on-click-action="true"
          :close-on-popstate="true"
           @select="select"
           description="选择添加方式"
         />

    </div>
</template>
<script>
    import Vue from 'vue';
    import { Toast,AddressList,ActionSheet,Empty } from 'vant';
    import { getList } from "@/api/address";
    import { wechatInit } from "@/api/user";
    import { chooseAddress } from "@/api/order";
    import { change } from "@/api/address";
    // import wx from 'weixin-js-sdk';
    import JmHead from '../head/head'

    Vue.use(AddressList).use(ActionSheet).use(Empty)
    export default {
        name: 'addrList',
        components: {
            JmHead
        },
        data () {
            return {
                addrList: [],
                data: [],
                haveLists: false,
                defaultAddr: "0",
                pageHeight: 0,
                hasOrder: false,
                showModel: false,
                actions: [
                    {name: '自行输入地址'},
                    {name: '导入微信地址'}
                ],
                urlLink:'',
            }
        },
        methods: {
            getList() {
                getList({}).then(res => {
                    this.data = []
                    this.addrList = []
                    if(res.data.address.length === 0){
                        this.haveLists = false
                    } else {
                        this.haveLists = true
                        this.data = res.data.address
                        res.data.address.filter(item => {
                            let obj = {}
                            obj.id = item.id.toString()
                            obj.name = item.accepter_name
                            obj.tel = item.accepter_phone
                            obj.address = item.province_name + item.city_name + item.district_name + item.detail_address,
                            obj.isDefault = item.id === res.data.address_id ? true : false
                            // this.defaultAddr = res.data.address_id.toString()
                            this.addrList.push(obj)
                        })
                    }

                })
            },
            onEdit(item, index) {
                const obj = this.data[index]
                obj.isDefault = obj.id.toString() === this.defaultAddr ? 1 : 0
                this.$router.push({path: '/addr/add', query: obj})
            },
            onAdd() {
                this.showModel = true
            },
            active(item, index) {
                if (!this.hasOrder) {
                    return
                }
                chooseAddress({id: this.$route.query.order_id, ad_id: item.id}).then(res => {
                    // this.$router.go(-1);
                    this.$router.push({path: '/order/detail', query: {id:this.$route.query.order_id}})
                })

            },
            select(action, index) {
                if (index === 0) {
                  this.$router.push({path: '/addr/add', query: {id: 'new'}})
                } else {

                    this.urlLink =  /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : window.entryUrl;
                    // console.log("window.entryUrl:"+window.entryUrl)
                    const that = this
                    wechatInit({url: this.urlLink}).then(res=>{
                        console.log('wechatInit')
                        console.log(res)
                        if (res.code === 20000) {
                            console.log('wechatInit成功')
                            wx.config({
                              debug: false,
                              appId: res.data.appid,
                              timestamp: res.data.timestamp,
                              nonceStr: res.data.noncestr,
                              signature: res.data.signature,
                              jsApiList: ['openAddress']
                            });
                            console.log('openAddress')
                            wx.ready(function() {
                                console.log('ready')
                                wx.openAddress({
                                  success: function (res) {
                                      console.log('openAddress')
                                      console.log(res)
                                      const obj = {
                                          id: 'new',
                                          accepter_name: res.userName,
                                          accepter_phone: res.telNumber,
                                          province_name: res.provinceName,
                                          city_name: res.cityName,
                                          district_name: res.countryName,
                                          detail_address: res.detailInfo,
                                          national_code: res.nationalCode,
                                          isDefault: 0
                                      }
                                      change(obj).then(res => {
                                          if (res.code === 20000) {
                                              Toast.success({message: '导入成功', duration: 2000})
                                              that.getList()
                                          } else {
                                              Toast.fail({message: res.info, duration: 2000})
                                          }
                                      })
                                  },
                                  fail: function (res) {
                                      console.log('fail')
                                      console.log(res)
                                  }
                                });
                            })
                        } else {
                            console.log('wechatInit失败')
                        }
                    })
                }
            }
        },
        beforeRouteEnter(to, from, next) {

          //如果是ios环境
          if( /iPhone|mac|iPod|iPad/i.test(navigator.userAgent) ){
            // 记录进入app时的url
            if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
              window.entryUrl = location.href.split('#')[0]
            }
            // 将http://028h5.cn/?i=xxxxxxxxxx 转为http://028h5.cn/index?i=xxxxxxxxxx
            // if( window.entryUrl.indexOf('?') != -1 ){
            //   window.entryUrl = window.entryUrl.split('?')[0]
            // }
            // 进行签名的时候  Android 不用使用之前的链接， ios 需要
            window.entryUrl =  /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : window.entryUrl;
          }
          else{
            window.entryUrl = window.location.origin + to.path
          }
          console.log("window.entryUrl"+window.entryUrl);
          console.log("to.path"+to.path);
          console.log("location.pathname"+location.pathname);
          console.log("to.fullPath"+to.fullPath);
        	var u = navigator.userAgent;
        	  var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        	  // XXX: 修复iOS版微信HTML5 History兼容性问题
        	  if (isiOS && to.path !== location.pathname) {
        	    // 此处不可使用location.replace
              console.log("跳转新页面");
        	    location.assign(to.fullPath)
        	  } else {
        	    next()
        	  }
        },
        activated: function () {
            if (this.$route.query.order_id !== undefined) {
                this.hasOrder = true
            }
            this.pageHeight = window.innerHeight
            this.getList()

            this.$refs.head.setNavBarUrl()
        }
    }
</script>

<style>
    .vant-image{
        margin-top: 2rem;
    }
    .vant-image .van-empty__image{
        width: 90px;
        height: 90px;
    }
</style>
<style lang="stylus" scoped>
    .addrList
        width 100%
        height 100%
        overflow hidden
        background #f5f5f5
        .addrList_menu
            width 100%
            overflow hidden

            .van-address-list
                padding-bottom 0
            p
                font-size .24rem
                color #9e9e9e
                text-align center
                line-height 1.5
                padding .3rem 0
            .footer_tip
                font-size .26rem
                text-align center
                width 100%
                color #000
                line-height .44rem
                padding .3rem
        .addrList_noaddr
            width 100%
            overflow hidden
            display block
            height 0
            padding-bottom 155%
            background #fff
            img
                width 100%
                margin-top 1rem
            p
                font-size .24rem
                color #9e9e9e
                text-align center
                line-height 1.5
                padding .3rem 0

        .btns_div
            width 100%
            overflow hidden
            padding .2rem .3rem
            position fixed
            bottom 0
            left 0
            background #fff
            button
                width 45%
                border 1px solid red
                padding-left .2rem
                line-height .7rem
                height .7rem
                font-size .28rem
                color #fff
                border-radius .6rem
                display block
                text-align center
                background red url(//img.haoyunbang.cn/m/img/ico_mobil_hp_address_01.png) no-repeat;
                background-size .3rem
                background-position: .4rem center

            .wexin_btn
                border 1px solid #f1a240
                background-color  #f1a240
</style>
